<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/4 0004
 * Time: 上午 10:00
 */
namespace app\admin\controller;

use think\Db;
use \think\Request;
use think\Session;
class count extends Permissions
{

    /**
    *总交易量     玩家总数    今日交易量
    */
    public function record()
    {
        $res    =   Session::get("admin_cate_id");//获取登陆时的admin_cate_id,控制器comment中的admin_cate_id(127行）
        $ress   =   Session::get("admin");//获取登陆时的admin，控制器comment中的admin(126行）
        $list   =   Db::name('admin')->where('id',$ress)->value('name');
        $uid    =   Db::name('agent')->where('phone',$list)->value('id');
        $pid    =   Db::name('ratio')->where('agent_id',$uid)->value('pid');


        $game_code  =   Db::name('relation')->where('user_id',$uid)->value('invitation_code');
        $game_id    =   Db::name('relation')->where('invitation_code',$game_code)->select();

        if($res != 1){
             //总交易量
            $total_trade     =   Db::name('order')->where('agent_id',$uid)->sum('recharge_money');
            //佣金总数
            $total_charge    =   Db::name('charge')->where('agent_id',$uid)->sum('charge_money');
            //玩家总数
            $request         =   Db::name('ratio')->where('agent_id',$uid)->value('request');
            $total_gameuser  =   Db::name('relation')->where('invitation_code',$request)->count();
            //获取当天时间
            $early_today     =   strtotime(date('Y-m-d' , time()));
            $late_today      =   strtotime("+1 day");
            //今日交易量
            $today_trade     =   Db::name('order')->where('finish_time' , 'between' , [$early_today , $late_today])->where('agent_id',$uid)->sum('recharge_money');
            //今日添加用户总数
            $today_gameuser  =   Db::name('relation')->where('add_time' , 'between' , [$early_today , $late_today])->where('invitation_code',$request)->count();
            //今日消耗房卡总数
            $Score           =   0;
            foreach ($game_id as $key => $value) {
                $uids   =   $value['game_user_id'];
                $nums   =   getSqlConnec('QPTreasureDB_CHUI', 'RecordFangKaCost')->where('CostTime' , 'between' , [$early_today , $late_today])->where("UserID='$uids'")->value('CostCount');
                $Score +=   $nums;
            }
            $today_charge = $Score;

            $beginThismonth =   mktime(0,0,0,date('m'),1,date('Y'));
            $endThismonth   =   mktime(23,59,59,date('m'),date('t'),date('Y'));

            //当月交易量
            $month_trade    =   Db::name('order')->where('finish_time' , 'between' , [$beginThismonth , $endThismonth])->where('agent_id',$uid)->sum('recharge_money');
            // 当月添加玩家总数
            $month_gameuser =   Db::name('relation')->where('add_time' , 'between' , [$beginThismonth , $endThismonth])->where('invitation_code',$request)->count();
            // 当月佣金总数
            $month_charge   =   Db::name('charge')->where('add_time' , 'between' , [$beginThismonth , $endThismonth])->where('agent_id',$uid)->sum('charge_money');
            if($pid == 0){
                //总代理下子集总交易量
                $list   =   Db::name('ratio')->where('agent_id',$uid)->select();
                $res    =   Db::name('ratio')->where('pid',$uid)->select();//查询所有二级代理商
                $lis    =   [];
                foreach ($res as $k => $v) {
                    //定义一个空数组为二级分类的名字
                    $res[$k]['child'] = [];
                    //查询二级分类。条件为父id等于等级分类的id
                    $lis = Db::name('ratio')->where('pid',$v['agent_id'])->select();
                }
                $agent   =   array_merge($res,$lis);//合并数组
                $agents  =   array_merge($agent,$list);//合并数组

                $num     =  0;
                foreach ($agents as $key => $value) {
                    $agent_id   =   $value['agent_id'];
                    $nums       =   Db::name('order')->where('agent_id',$agent_id)->sum('recharge_money');
                    $num        +=  $nums;
                }
                $this->assign('num',$num);
            }
        } else{
            //总交易量
            $total_trade    =   Db::name('order')->sum('recharge_money');
            //佣金总数
            $total_charge   =   Db::name('charge')->sum('charge_money');
            //玩家总数
            $total_gameuser =   getSqlConnec('QPAccountsDB_CHUI', 'AccountsInfo')->count();
            //获取当天时间
            $early_today    =   date('Y-m-d H:i:s' , strtotime(date('Y-m-d' , time())));
            $late_today     =   date('Y-m-d H:i:s' , strtotime("+1 day"));

            //当日交易量
            $today_trade    =   Db::name('order')->where('finish_time' , 'between' , [$early_today , $late_today])->sum('recharge_money');
            //今日用户总数
            $today_gameuser =   Db::name('relation')->where('add_time' , 'between' , [$early_today , $late_today])->count();
            //当日消耗房卡数总数
            $today_charge   =   getSqlConnec('QPTreasureDB_CHUI', 'RecordFangKaCost')->where('CostTime' , 'between' , [$early_today , $late_today])->count();

            $beginThismonth =   mktime(0,0,0,date('m'),1,date('Y'));
            $endThismonth   =   mktime(23,59,59,date('m'),date('t'),date('Y'));

            //当月交易量
            $month_trade    =   Db::name('order')->where('finish_time' , 'between' , [$beginThismonth , $endThismonth])->sum('recharge_money');
            //当月添加玩家总数
            $month_gameuser =   Db::name('relation')->where('add_time' , 'between' , [$beginThismonth , $endThismonth])->count();
            //当月佣金总数
            $month_charge   =   Db::name('charge')->where('add_time' , 'between' , [$beginThismonth , $endThismonth])->sum('charge_money');
        }

        $this->assign(['total_trade' => $total_trade , 'total_charge' => $total_charge ,
                     'total_gameuser' =>$total_gameuser , 'today_trade' => $today_trade,
                    'today_gameuser' => $today_gameuser,'month_trade' =>$month_trade,
                    'month_gameuser' =>$month_gameuser,'today_charge' =>$today_charge,
                    'month_charge' =>$month_charge]);
        $this->assign('pid',$pid);
        return $this->fetch();
    }

    /**
    *  旗力币总数
    */
    public function goldrecord()
    {
        $res    =   Session::get("admin_cate_id");//获取登陆时的admin_cate_id,控制器comment中的admin_cate_id(127行）
        $ress   =   Session::get("admin");//获取登陆时的admin，控制器comment中的admin(126行）
        $list   =   Db::name('admin')->where('id',$ress)->value('name');
        $uid    =   Db::name('agent')->where('phone',$list)->value('id');
        if($res != 1){
            $request    =   Db::name('ratio')->where('agent_id',$uid)->value('request');
            $gameuser = Db::name('relation')->where('invitation_code',$request)->select();
            $Score=0;
        foreach ($gameuser as $key => $value) {
            $uid    =   $value['game_user_id'];
            $nums   =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where("UserID='$uid'")->value('Score');
            $Score +=   $nums;
        }
        $web['gold_num'] =  $Score;
        $InsureScore     =  0;
        foreach ($gameuser as $key => $value) {
            $uid    =   $value['game_user_id'];
            $nums   =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->where("UserID='$uid'")->value('InsureScore');
            $InsureScore += $nums;
        }
        $web['roomcard_num']    =   $InsureScore;

       

        $web['recharge_num']    =   Db::name('order')->where('agent_id',$uid)->sum('recharge_money');

        $web['send_roomcard']   =   Db::name('order')->where('agent_id',$uid)->sum('qili_gold');

         $CostCount=0;
        foreach ($gameuser as $key => $value) {
            $uid = $value['game_user_id'];
            $nums   =   getSqlConnec('QPTreasureDB_CHUI', 'RecordFangKaCost')->where("UserID='$uid'")->value('CostCount');
            $CostCount += $nums;
        }

        $web['cost_roomcard']   =   $CostCount;

        }else{


        $web['gold_num']        =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->sum('Score');

        $web['roomcard_num']    =   getSqlConnec('QPTreasureDB_CHUI', 'GameScoreInfo')->sum('InsureScore');

        $web['recharge_num']    =   Db::name('order')->sum('recharge_money');

        $web['send_roomcard']   =   Db::name('order')->sum('qili_gold');

        $web['cost_roomcard']   =   getSqlConnec('QPTreasureDB_CHUI', 'RecordFangKaCost')->sum('CostCount');
        }
        $this->assign('web',$web);
        return $this->fetch();
    }

    /*
     * 玩家7天统计
     */
    public function user_day()
    {
        $res    =   Session::get("admin_cate_id");//获取登陆时的admin_cate_id,控制器comment中的admin_cate_id(127行）
        $ress   =   Session::get("admin");//获取登陆时的admin，控制器comment中的admin(126行）
        $list   =   Db::name('admin')->where('id',$ress)->value('name');
        $uid    =   Db::name('agent')->where('phone',$list)->value('id');
        $request=   Db::name('ratio')->where('agent_id',$uid)->value('request');
     

        $day    =   Request::instance()->param('day')&& in_array(intval(Request::instance()->param('day')) , [7 , 30 , 180]) ? intval(Request::instance()->param('day')) : 7;
        $star   =   strtotime(date('Y-m-d H:i:s' , strtotime("-$day days")));
        $end    =   strtotime(date('Y-m-d H:i:s' , time()));
        if($res != 1){
            $gameusers   =   Db::name('relation')->where('invitation_code',$request)->where('add_time' , 'between' , [$star , $end])->field('add_time , count(*) as count')->group('add_time')->select();
            $gameuser    =   [];
            foreach($gameusers as $k=>$v){
                $gameuser[date("m-d" , $v['add_time'])][]  =   $v['count'];
            }
        }else{
            $gameusers  =   getSqlConnec("QPAccountsDB_CHUI" , 'AccountsInfo')->where('RegisterDate' , 'between' , [date('Y-m-d H:i:s' , strtotime("-$day days")) , date('Y-m-d H:i:s' , time())])->field('RegisterDate , count(*) as count')->group('RegisterDate')->select();
            $gameuser   =   [];
            foreach($gameusers as $k=>$v){
                $gameuser[date("m-d" , strtotime($v['RegisterDate']))][]  =   $v['count'];
            }
        }

     
        $days   =   $num    =   '';
        foreach($gameuser as $k=>$v){
            $days   .=  $k . ',';
            $num    .=  array_sum($v) . ',';   
        }

        // dump($days);dump($num);exit;
        $this->assign(['days' => trim($days , ',') , 'num' => trim($num , ',')]);
        return $this->fetch();
    }

    /**
    *交易统计
    */
    public function charge_day()
    {
        $day    =   Request::instance()->param('day') && in_array(intval(Request::instance()->param('day')) , [7 , 30 , 180]) ? intval(Request::instance()->param('day')) : 7;

        $res    =   Session::get("admin_cate_id");//获取登陆时的admin_cate_id,控制器comment中的admin_cate_id(127行）
        $ress   =   Session::get("admin");//获取登陆时的admin，控制器comment中的admin(126行）
        $list   =   Db::name('admin')->where('id',$ress)->value('name');
        $uid    =   Db::name('agent')->where('phone',$list)->value('id');
        if($res != 1){
             $orders     =   Db::name('order')->where('finish_time' , 'between' , [strtotime("-$day days") , strtotime(date('Y-m-d' , time()))])
                        ->where('agent_id',$uid)->field('finish_time , sum(recharge_money) as sum')->group('finish_time')->select();
        }else{
             $orders     =   Db::name('order')->where('finish_time' , 'between' , [strtotime("-$day days") , strtotime(date('Y-m-d' , time()))])
                        ->field('finish_time , sum(recharge_money) as sum')->group('finish_time')->select();
        }

        $order      =   [];
        foreach ($orders as $key => $value) {
              $order[date('m-d' , $value['finish_time'])][]   =   $value['sum'];
        }  

        $days   =   $money    =   '';
        foreach($order as $k=>$v){
            $days     .=  $k . ',';
            $money    .=  array_sum($v) . ',';   
        }
         $this->assign(['days' => trim($days , ',') , 'money' => trim($money , ',')]);
        return $this->fetch();
    }

    /**
    *当日交易排行
    */
    public function headay()
    {
        $res    =   Session::get("admin_cate_id");//获取登陆时的admin_cate_id,控制器comment中的admin_cate_id(127行）
        $ress   =   Session::get("admin");//获取登陆时的admin，控制器comment中的admin(126行）
        $list   =   Db::name('admin')->where('id',$ress)->value('name');
        $uid    =   Db::name('agent')->where('phone',$list)->value('id');
        $code   =   Db::name('ratio')->where('agent_id',$uid)->value('request');
        $user   =   Db::name('relation')->where('invitation_code',$code)->select();
        $count  =   array();
        foreach ($user as $key => $value) {
            $uid    =    $value['game_user_id'];
            $count[$key]['CostCount'] =  getSqlConnec('QPTreasureDB' , 'RecordFangKaCost')->where("UserID='$uid'")->where('CostTime', 'between', [date('Y-m-d') , date('Y-m-d' , time())])->sum('CostCount');
            $count[$key]['game_user_id'] = $value['game_user_id'];
            $count[$key]['time'] = date('Y-m-d');
        }
        foreach ($count as $key=>$value){
            $id[$key] = $value['CostCount'];
        }
      if($count){
          array_multisort($id,SORT_NUMERIC,SORT_DESC,$count);
          $result = array_slice($count, 0,10);
      }else{
          $result = array();
      }
    
      $this->assign('result',$result);
      return $this->fetch();
    }


}